package top.caoayu.base.controller;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.caoayu.common.response.Result;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;

@Controller
public class HelloController {
    @GetMapping("/")
    public String index(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "login";
        } else {
            return "index";
        }
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session) {
        if (username.equals("admin") && password.equals("123456")) {
            session.setAttribute("user", username);
            return "index";
        } else {
            model.addAttribute("status", "用户名或密码错误");
            return "login";
        }
    }

    @PostMapping("/pay")
    @ResponseBody
    public Map<String,Boolean> pay(@RequestParam String account,  HttpSession session) throws JSONException {
        HashMap<String, Boolean> map = new HashMap<>();
        if(session.getAttribute("user") == null){
            map.put("success", false);
            return map;
        }
        if (Objects.equals(session.getAttribute("user").toString(), account)) {
            map.put("success", true);
        } else {
            map.put("success", false);
        }
        return map;
    }

    @GetMapping("/csrf")
    public String csrf() {
        return "csrf";
    }

}
